package com.zzxx.wechat.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.zzxx.wechat.common.ArcterySkuVo;
import com.zzxx.wechat.common.ArcterySpuVo;
import com.zzxx.wechat.dao.ArcteryxBindDao;
import com.zzxx.wechat.dao.ArcteryxSkuDao;
import com.zzxx.wechat.dao.ArcteryxSpuDao;
import com.zzxx.wechat.entity.ArcteryxBind;
import com.zzxx.wechat.entity.ArcteryxSku;
import com.zzxx.wechat.entity.ArcteryxSpu;
import com.zzxx.wechat.exception.BusinessException;
import com.zzxx.wechat.service.ArcteryxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.zzxx.wechat.util.SkuComparator;
import java.util.List;

@Slf4j
@Controller
public class IndexController {


    @Autowired
    ArcteryxService arcteryxService;

    @Autowired
    ArcteryxSpuDao arcteryxSpuDao;
    @Autowired
    ArcteryxSkuDao arcteryxSkuDao;

    @Autowired
    ArcteryxBindDao arcteryBindDao;


    @RequestMapping("/index")
    public ModelAndView index(Integer bindId) {

        ArcteryxBind arcteryBind = arcteryBindDao.getById(bindId);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index2");
        //根据链接查询
        //  List<ArcteryxSku> arcteryxSkuList = arcteryxSkuDao.list();
        List<ArcteryxSku> arcteryxSkuList;
        try {
            arcteryxSkuList = arcteryxService.analysisUrl(arcteryBind.getSpuUrl());
        } catch (BusinessException e) {
            log.error("", e);
            modelAndView.addObject("message", e.getMessage());
            return modelAndView;
        } catch (Exception e) {
            log.error("", e);
            modelAndView.addObject("message", "解析地址发生失败,请联系管理员");
            return modelAndView;
        }
        if (CollectionUtil.isEmpty(arcteryxSkuList)) {
            modelAndView.addObject("message", "该商品链接未查询到库存信息");
            return modelAndView;
        }
        ArcteryxSku firstSku = arcteryxSkuList.get(0);

        ArcteryxSpu acteryxSpu = arcteryxSpuDao.queryBySpuId(firstSku.getSpuId());
        ArcterySpuVo arcterySpuVo = new ArcterySpuVo();
        arcterySpuVo.setSpuId(firstSku.getSpuId());
        arcterySpuVo.setSpuName(acteryxSpu.getSpuName());
        List<ArcterySkuVo> arcterySkuVos = ArcterySkuVo.convert2VoList(arcteryxSkuList);
        arcterySkuVos.sort(new SkuComparator());
        arcterySpuVo.setArcterySkuVos(arcterySkuVos);
        modelAndView.addObject("arcterySpuVo", arcterySpuVo);
        modelAndView.setViewName("index2");
        return modelAndView;
    }
}
